
/**
 * 全局socket
 */
const url = "ws://127.0.0.1:8080/renren-fast/app/global/";
import userUtils from "@/utils/userUtils.js"
export default {
	websocket: null,
	onMessageCallbacks : [],
	open() {
		let token = userUtils.getToken();
		if(token == null || token == ''){//token为null代表未登录，就不需要连接socket了
			return;
		}
		let newUrl = url + token
		if ('WebSocket' in window) {
			//连接WebSocket节点
			this.websocket = new WebSocket(newUrl);
		} else {
			alert('Not support websocket')
		}
		//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
		window.onbeforeunload = function() {
			this.websocket.close();
		}
		this.websocket.onerror = ()=>{
			console.log("连接异常")
		}
		//连接成功建立的回调方法
		this.websocket.onopen = ()=>{
			console.log("连接成功")
		}
		//接收到消息的回调方法
		this.websocket.onmessage = ()=>{
			let result =JSON.parse(event.data);
			this.onMessageCallbacks.forEach((callback)=>{
				callback(result)
			})
		}
		//连接关闭的回调方法
		this.websocket.onclose = ()=>{
			console.log("连接关闭")
		}
	},
	onmessage(callback){
		this.onMessageCallbacks.push(callback);
	},
	close(){
		this.websocket.close()
		this.websocket = null;
	}
	
}